package com.chenchen.code.guava.concurrent;

import com.google.common.util.concurrent.*;
import com.sun.istack.internal.Nullable;

import java.util.concurrent.*;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/3 13:27
 */
public class ListenableFutureExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //ListenableFuture();
        CompletableFuture();
    }

    public static void future() throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<Integer> future = service.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 10;
        });

        Object result = future.get();
        System.out.println(result);
    }

    public static void ListenableFuture() {
        ExecutorService service = Executors.newFixedThreadPool(2);
        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(service);
        ListenableFuture<Integer> future = listeningExecutorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return 100;
        });
        //future.addListener(() -> System.out.println("I am finished"), service);
        Futures.addCallback(future, new MyCallBack(), service);
    }

    static class MyCallBack implements FutureCallback<Integer> {

        @Override
        public void onSuccess(@Nullable Integer result) {
            System.out.println("I am finished and the result is " + result);
        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    }

    public static void CompletableFuture() {
        ExecutorService service = Executors.newFixedThreadPool(2);
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 100;
        }, service);
        future.whenComplete((v, t) -> System.out.println("I am finished and the result is " + v));
    }
}